﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using MementoClientConnectorInterfaces;
using MementoClientConnectorLibrary.OnTime2009.Tasks;
using MementoClientConnectorLibrary.OnTime2009.Users;

namespace MementoClientConnectorLibrary
{
    [Export(typeof(IMementoClientConnector))]
    public class OnTimeClientConnector : IMementoClientConnector
    {
        public List<TaskSourceSystemConfiguration> GetConfigurations()
        {
            return new List<TaskSourceSystemConfiguration>() { new TaskSourceSystemConfiguration() { UniqueID = "OnTime2008" } };
        }

        public List<MementoClientConnectorInterfaces.Task> GetTasksForUser(string configurationUniqueID, string userName)
        {
            List<MementoClientConnectorInterfaces.Task> tasksToReturn = new List<MementoClientConnectorInterfaces.Task>();

            string configuredUrl = ConfigurationManager.AppSettings["Ontime.Url"];
            string guidString = ConfigurationManager.AppSettings["Ontime.Guid"];
            Guid guid = new Guid(guidString);
            int userId = this.LookupUserIdFromUsername(guid, userName);

            var connectionString = ConfigurationManager.ConnectionStrings["OnTime.Database"].ConnectionString;
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);
            
            using (conn)
            {
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("buildtaskprojecthierachy", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("userID", userId));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("includeCompleted", false));
                conn.Open();
                var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                
                // The Tasks data set is the second set in the Stored Proc return result
                reader.NextResult();

                while(reader.Read())
                {
                    var task = new MementoClientConnectorInterfaces.Task();
                    task.TaskName = Convert.ToString(reader["Name"]);
                    task.TaskID = Convert.ToString(reader["TaskId"]);
                    task.ProjectID = Convert.ToString(reader["ProjectID"]);
                    tasksToReturn.Add(task);
                }
                
            }

            return tasksToReturn;

        }

        private int LookupUserIdFromUsername(Guid guid, string userName)
        {
            var userHandler = new UserHandler();
            var userDataSet = userHandler.GetAllUsers(guid);
            var reader = userDataSet.CreateDataReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    if (Convert.ToString(reader["Email"]) == userName)
                    {
                        return Convert.ToInt32(reader["UserId"]);
                    }
                }
            }

            return 0;
        }
    }
}
